﻿using System;
using System.Data.SqlClient;

namespace HashFoo.SqlServer.TransientDbConnection
{
    /// <summary>
    /// Generic <see cref="ISqlExceptionProvider"/> using a function.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class FuncSqlExceptionProvider<T> : ISqlExceptionProvider
        where T : Exception
    {
        readonly Func<T, SqlException> _sqlExProvider;

        public FuncSqlExceptionProvider(Func<T, SqlException> sqlExProvider)
        {
            _sqlExProvider = sqlExProvider;
        }

        /// <summary>
        /// Gets a sql exception from the type of a specific exception.
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        public SqlException GetFrom<TEx>(TEx ex) where TEx : Exception
        {
            var myEx = ex as T;
            if (myEx == null) throw new InvalidOperationException("Exception not type T: " + typeof(T));

            return GetSqlException(myEx);
        }

        /// <summary>
        /// True if the provider can get a <see cref="SqlException"/> from the <typeparamref name="TEx"/> exception.
        /// </summary>
        /// <typeparam name="TEx"></typeparam>
        /// <param name="ex"></param>
        /// <returns></returns>
        public bool Handles<TEx>(TEx ex) where TEx : Exception
        {
            return typeof(T).IsAssignableFrom(typeof(TEx));
        }

        SqlException GetSqlException(T ex)
        {
            return _sqlExProvider(ex);
        }
    }
}